package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.tianji.api.cache.CategoryCache;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.client.search.SearchClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.config.AliyunContentSecurityTemplate;
import com.tianji.learning.config.AuditResult;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionAdminPageQuery;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionAdminVO;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2024-06-25
 */
@Service
@RequiredArgsConstructor
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {
    private final InteractionReplyMapper replyMapper;
    private final UserClient userClient;
    private final SearchClient searchClient;
    private final CourseClient courseClient;
    private final CatalogueClient catalogueClient;
    private final CategoryCache categoryCache;
    private final AliyunContentSecurityTemplate contentSecurityTemplate;



    /**
     * 1、新增互动问题 (Day5- 课堂1)
     *
     * @param questionDTO
     */
    @Override
    public void saveQuestion(QuestionFormDTO questionDTO) {
        // 0、问题检测
        List<String> checkTexts = Lists.newArrayList(questionDTO.getTitle(),questionDTO.getDescription());
        AuditResult auditResult = contentSecurityTemplate.textAudit(checkTexts);
        if (!auditResult.isPass()) {
            throw new BadRequestException("问题标题或问题描述不合规！详细：["+auditResult.getReason()+"]");
        }

        // 1、数据拷贝
        InteractionQuestion question = BeanUtils.copyBean(questionDTO, InteractionQuestion.class);

        // 2、补充用户ID
        question.setUserId(UserContext.getUser());

        // 3、新增数据
        save(question);
    }

    /**
     * 2、分页查询互动问题 (Day5- 课堂2)
     *
     * @param query
     */
    @Override
    public PageDTO<QuestionVO> pageQuery(QuestionPageQuery query) {
        // 1、参数校验：课程ID和小节ID不能同时为空
        Long courseId = query.getCourseId();
        Long sectionId = query.getSectionId();
        if (courseId == null && sectionId == null) {
            throw new BadRequestException("课程ID和小节ID不能同时为空!");
        }

        // 2、分页查询
        // select * from interaction_question where course_id = ? or section_id = ? and user_id = ? and hidden = 0
        // order by create_time desc limit ?,?
        Page<InteractionQuestion> pageResult = lambdaQuery()
                .select(InteractionQuestion.class, column -> !column.getColumn().equals("description"))  // select 断言，只查询description以外的字段
                .eq(ObjectUtil.isNotNull(courseId), InteractionQuestion::getCourseId, courseId)
                .eq(ObjectUtil.isNotNull(sectionId), InteractionQuestion::getSectionId, sectionId)
                .eq(query.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(InteractionQuestion::getHidden, false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = pageResult.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(pageResult);
        }

        // 3、补充信息查询：查询提问者信息、查询最近一次回答信息
        // 3.1、收集提问者的ID集合、最近一次回答ID集合
        Set<Long> userIds = new HashSet<>(records.size());
        Set<Long> lastAnswerIds = new HashSet<>(records.size());
        for (InteractionQuestion record : records) {
            if (!record.getAnonymity()) {
                userIds.add(record.getUserId());
            }
            lastAnswerIds.add(record.getLatestAnswerId());
        }

        // 3.2、根据最近一次回答ID集合进行查询 -> 转成Map（最近一次回答ID： 最近一次回答信息对象）
        Map<Long, InteractionReply> replyMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(lastAnswerIds)) {
            List<InteractionReply> lastReplieList = replyMapper.selectBatchIds(lastAnswerIds);
            if (ObjectUtil.isNotEmpty(lastReplieList)) {
                for (InteractionReply reply : lastReplieList) {
                    replyMap.put(reply.getId(), reply);
                    if (!reply.getAnonymity()) {
                        userIds.add(reply.getUserId());  // 收集最近一次回答者的ID集合
                    }
                }
            }
        }

        // 3.3、根据用户ID集合远程调用查询用户信息集合 -> 转成Map （用户ID： 用户信息对象）
        Map<Long, UserDTO> userMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(userIds)) {
            List<UserDTO> userInfoList = userClient.queryUserByIds(userIds);
            if (ObjectUtil.isNotEmpty(userInfoList)) {
                userMap = userInfoList.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
            }
        }

        // 4、循环遍历分页数据，封装VO集合
        List<QuestionVO> voList = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            // 4.1、拷贝数据
            QuestionVO vo = BeanUtils.copyBean(record, QuestionVO.class);

            // 4.2、补充提问者信息（提问者昵称、头像）
            if (!record.getAnonymity()) {
                UserDTO userInfo = userMap.get(record.getUserId());
                if (ObjectUtil.isNotEmpty(userInfo)) {
                    vo.setUserName(userInfo.getName());
                    vo.setUserIcon(userInfo.getIcon());
                }
            }

            // 4.3、补充最近一次回答信息（最近一次回答者昵称、最近一次回答内容）
            InteractionReply lastReply = replyMap.get(record.getLatestAnswerId());
            if (ObjectUtil.isNotEmpty(lastReply)) {
                vo.setLatestReplyContent(lastReply.getContent());
                if (!lastReply.getAnonymity()) {
                    UserDTO userInfo = userMap.get(lastReply.getUserId());
                    if (ObjectUtil.isNotEmpty(userInfo)) {
                        vo.setLatestReplyUser(userInfo.getName());
                    }
                }
            }

            // 4.4、将vo添加至volist
            voList.add(vo);
        }

        // 5、组装PageDTO并返回
        return PageDTO.of(pageResult, voList);
    }

    /**
     * 3、根据ID查询互动问题 (Day5- 课堂3)
     *
     * @param id 问题ID
     */
    @Override
    public QuestionVO queryById(Long id) {
        // 1、根据ID查询问题
        InteractionQuestion question = this.getById(id);
        if (ObjectUtil.isEmpty(question) || question.getHidden()) {
            return null;
        }

        // 2、查询提问者信息
        UserDTO userInfo = null;
        if (!question.getAnonymity()) {
            userInfo = userClient.queryUserById(question.getUserId());
        }

        // 3、封装Vo并返回
        QuestionVO vo = BeanUtils.copyBean(question, QuestionVO.class);
        if (ObjectUtil.isNotEmpty(userInfo)) {
            vo.setUserName(userInfo.getName());
            vo.setUserIcon(userInfo.getIcon());
        }
        return vo;
    }

    /**
     * 4、管理端 - 分页查询互动问题 (Day5- 课堂4)
     *
     * @param query
     */
    @Override
    public PageDTO<QuestionAdminVO> adminPageQuery(QuestionAdminPageQuery query) {
        // 1、调用ES处理课程名称，得到课程ID集合
        List<Long> courseIds = null;
        if (ObjectUtil.isNotEmpty(query.getCourseName())) {
            courseIds = searchClient.queryCoursesIdByName(query.getCourseName());
            if(ObjectUtil.isEmpty(courseIds)){
                return PageDTO.empty(0L,0L);
            }
        }

        // 2、分页查询问题列表
        // select * from interaction_question where course_id in (#{id},#{id})
        // and status = #{status} and create_time between #{beginTime} and #{endTime} order by create_time desc limit 0,10
        Page<InteractionQuestion> pageResult = this.lambdaQuery()
                .in(ObjectUtil.isNotEmpty(courseIds), InteractionQuestion::getCourseId, courseIds)
                .eq(ObjectUtil.isNotEmpty(query.getStatus()), InteractionQuestion::getStatus, query.getStatus())
                .ge(ObjectUtil.isNotEmpty(query.getBeginTime()), InteractionQuestion::getCreateTime, query.getBeginTime())
                .le(ObjectUtil.isNotEmpty(query.getEndTime()), InteractionQuestion::getCreateTime, query.getEndTime())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = pageResult.getRecords();
        if(ObjectUtil.isEmpty(records)){
            return PageDTO.empty(pageResult);
        }

        // 3、提前查询缺失的数据
        // 3.0、收集各种业务ID
        Set<Long> userIds = new HashSet<>();  // 用户ID集合
        Set<Long> cIds = new HashSet<>();     // 课程ID集合
        Set<Long> cateIds = new HashSet<>();  // 章节ID集合
        for (InteractionQuestion record : records) {
            userIds.add(record.getUserId());
            cIds.add(record.getCourseId());

            cateIds.add(record.getChapterId());
            cateIds.add(record.getSectionId());
        }

        // 3.1、根据用户ID集合查询用户数据
        List<UserDTO> userInfoList = userClient.queryUserByIds(userIds);
        Map<Long, String> userInfoMap = new HashMap<>(userIds.size());
        if(ObjectUtil.isNotEmpty(userInfoList)){
           userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserDTO::getId, UserDTO::getName));
        }

        // 3.2、根据课程ID集合查询课程数据
        List<CourseSimpleInfoDTO> couseInfoList = courseClient.getSimpleInfoList(cIds);
        Map<Long, CourseSimpleInfoDTO> couseInfoMap = new HashMap<>(cIds.size());
        if(ObjectUtil.isNotEmpty(couseInfoList)){
            couseInfoMap = couseInfoList.stream().collect(Collectors.toMap(CourseSimpleInfoDTO::getId, Function.identity()));
        }

        // 3.3、根据章节ID集合查询章节数据
        List<CataSimpleInfoDTO> cataInfoList = catalogueClient.batchQueryCatalogue(cateIds);
        Map<Long, String> cataInfoMap = new HashMap<>(cateIds.size());
        if(ObjectUtil.isNotEmpty(cataInfoList)){
            cataInfoMap = cataInfoList.stream().collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }

        // 4、循环列表，填充各种数据
        List<QuestionAdminVO> voList = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            // 4.1、属性拷贝
            QuestionAdminVO adminVO = BeanUtils.copyBean(record, QuestionAdminVO.class);

            // 4.2、填充用户昵称
            adminVO.setUserName(userInfoMap.getOrDefault(record.getUserId(),""));

            // 4.3、填充课程名称 和 分类信息
            CourseSimpleInfoDTO courseInfo = couseInfoMap.get(record.getCourseId());
            if(ObjectUtil.isNotEmpty(courseInfo)){
                adminVO.setCourseName(courseInfo.getName());
                adminVO.setCategoryName(categoryCache.getCategoryNames(courseInfo.getCategoryIds()));
            }

            // 4.4、填充章节名称
            adminVO.setChapterName(cataInfoMap.getOrDefault(record.getChapterId(),""));
            adminVO.setSectionName(cataInfoMap.getOrDefault(record.getSectionId(),""));

            // 4.5、填充回答数量
            adminVO.setAnswerAmounts(record.getAnswerTimes());

            // 4.6、添加vo至volist
            voList.add(adminVO);
        }

        // 5、封装DTO并返回
        return PageDTO.of(pageResult, voList);
    }

    /**
     * 5、根据ID删除互动问题（Day5 - 实战）
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询当前问题
        InteractionQuestion q = getById(id);
        if (q == null) {
            return;
        }
        // 3.判断是否是当前用户的问题
        if (!q.getUserId().equals(userId)) {
            // 不是，抛出异常
            throw new BadRequestException("无权删除他人的问题");
        }
        // 4.删除问题
        removeById(id);
        // 5.删除回答
        replyMapper.delete(
                new QueryWrapper<InteractionReply>().lambda().eq(InteractionReply::getQuestionId, id)
        );
    }

    /**
     * 6、根据ID修改互动问题（Day5 - 实战）
     *
     * @param id
     * @param questionDTO
     */
    @Override
    public void updateQuestion(Long id, QuestionFormDTO questionDTO) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询当前问题
        InteractionQuestion q = getById(id);
        if (q == null) {
            throw new BadRequestException("问题不存在");
        }
        // 3.判断是否是当前用户的问题
        if (!q.getUserId().equals(userId)) {
            // 不是，抛出异常
            throw new BadRequestException("无权修改他人的问题");
        }
        // 4.修改问题
        InteractionQuestion question = BeanUtils.toBean(questionDTO, InteractionQuestion.class);
        question.setId(id);
        updateById(question);
    }

    /**
     * 7、管理端根据ID查询互动问题（Day5 - 实战）
     *
     * @param id
     * @return
     */
    @Override
    public QuestionAdminVO queryQuestionByIdAdmin(Long id) {
        // 1.根据id查询问题
        InteractionQuestion question = getById(id);
        if (question == null) {
            return null;
        }
        // 2.转PO为VO
        QuestionAdminVO vo = BeanUtils.copyBean(question, QuestionAdminVO.class);
        // 3.查询提问者信息
        UserDTO user = userClient.queryUserById(question.getUserId());
        if (user != null) {
            vo.setUserName(user.getName());
            vo.setUserIcon(user.getIcon());
        }
        // 4.查询课程信息
        CourseFullInfoDTO cInfo = courseClient.getCourseInfoById(
                question.getCourseId(), false, true);
        if (cInfo != null) {
            // 4.1.课程名称信息
            vo.setCourseName(cInfo.getName());
            // 4.2.分类信息
            vo.setCategoryName(categoryCache.getCategoryNames(cInfo.getCategoryIds()));
            // 4.3.教师信息
            List<Long> teacherIds = cInfo.getTeacherIds();
            List<UserDTO> teachers = userClient.queryUserByIds(teacherIds);
            if (ObjectUtil.isNotEmpty(teachers)) {
                vo.setTeacherName(teachers.stream()
                        .map(UserDTO::getName).collect(Collectors.joining("/")));
            }
        }
        // 5.查询章节信息
        List<CataSimpleInfoDTO> catas = catalogueClient.batchQueryCatalogue(
                List.of(question.getChapterId(), question.getSectionId()));
        Map<Long, String> cataMap = new HashMap<>(catas.size());
        if (ObjectUtil.isNotEmpty(catas)) {
            cataMap = catas.stream().collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }
        vo.setChapterName(cataMap.getOrDefault(question.getChapterId(), ""));
        vo.setSectionName(cataMap.getOrDefault(question.getSectionId(), ""));
        // 6.封装VO
        return vo;
    }

    /**
     * 8、管理端隐藏或显示问题（Day5 - 实战）
     *
     * @param id
     * @param hidden
     */
    @Override
    public void hiddenQuestion(Long id, Boolean hidden) {
        // 1.更新问题
        InteractionQuestion question = new InteractionQuestion();
        question.setId(id);
        question.setHidden(hidden);
        updateById(question);

        // 2.没有answerId，说明自己是回答，需要隐藏回答下的评论
        replyMapper.update(null,
                Wrappers.<InteractionReply>lambdaUpdate()
                        .set(InteractionReply::getHidden, hidden)
                        .eq(InteractionReply::getQuestionId, id)
        );
    }
}
